<template>
  <div>
    <el-dialog
      title="分配角色"
      :visible="isShowAssignRole"
      @close="closeDialog"
    >
      <el-checkbox-group v-model="selectedRoles">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-row type="flex" justify="center">
          <el-button size="small" @click="closeDialog">取消</el-button>
          <el-button type="primary" size="small" @click="btnOk">确认</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// 先获取所有的角色列表，做默认的展示
import { getRoleList } from '@/api/setting'
import { getUserDetailById } from '@/api/user'
import { assignRoles } from '@/api/employees'
// 定义方法获取角色数据
export default {
  name: 'AssignRole',
  props: {
    isShowAssignRole: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      selectedRoles: ['604e2aeb488be61b90b68776'],
      roleList: []
    }
  },
  created() {
    this.handleGetRoleList()
  },
  methods: {
    async btnOk() {
      await assignRoles({
        id: this.userId,
        roleIds: this.selectedRoles
      })
      this.$message.success('修改角色信息成功')
      this.closeDialog()
    },
    async handleGetRoleList() {
      const { rows } = await getRoleList()
      this.roleList = rows
    },
    async getSelectedRoles(id) {
      // 基于id获取当前用户的详细信息，包含当前用户的角色信息
      console.log('开始获取角色详情')
      const { roleIds } = await getUserDetailById(id)
      this.selectedRoles = roleIds || []
    },
    closeDialog() {
      // 清空数据
      this.selectedRoles = []
      this.$emit('update:isShowAssignRole', false)
    }
  }
}
</script>
